package com.wry.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

import java.util.Scanner;

/**
 * <h1> 客户端 <h1>
 *
 * @author wry
 * @since 2023/4/20 14:36
 */
public class NettyClient {

    public static void main(String[] args) {
        // 客户端不需要连接事件 只需要处理IO事件
        final EventLoopGroup workGroup = new NioEventLoopGroup();

        // 创建一个客户端
        final Bootstrap client = new Bootstrap();
        try {
            client.group(workGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel sc) throws Exception {
                            // 字符串添加编码处理器
                            sc.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8));
                        }
                    });
            // 与服务器连接
            final ChannelFuture channelFuture = client.connect("localhost", 8888).sync();
            System.out.println("正在发送消息到服务端~~~");
            for (;;){
                Scanner scanner = new Scanner(System.in);
                System.out.println("请输入消息内容：");
                final String s = scanner.nextLine();
                if (s.equals("close")){
                    System.out.println("正在关闭...");
                    return;
                }
                channelFuture.channel().writeAndFlush(s);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            // 优雅关闭
            workGroup.shutdownGracefully();
        }
    }
}
